﻿/*            Copyright(c) 2006-2008 Dave Sexton           *
 * http://www.codeplex.com/DocProject                      *
 * http://www.codeplex.com/DocProject/Project/License.aspx *
 ***********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace DaveSexton.DocProject
{
	[Serializable]
	public sealed class KeywordCollection : Collection<Keyword>
	{
		#region Public Properties
		public Keyword Root
		{
			get
			{
				return root;
			}
		}
		#endregion

		#region Private / Protected
		private readonly Keyword root;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructs a new instance of the <see cref="KeywordCollection" /> class.
		/// </summary>
		public KeywordCollection()
		{
		}

		/// <summary>
		/// Constructs a new instance of the <see cref="KeywordCollection" /> class.
		/// </summary>
		public KeywordCollection(Keyword root)
		{
			this.root = root;
		}

		/// <summary>
		/// Constructs a new instance of the <see cref="KeywordCollection" /> class.
		/// </summary>
		public KeywordCollection(IList<Keyword> list)
			: base(list)
		{
		}

		/// <summary>
		/// Constructs a new instance of the <see cref="KeywordCollection" /> class.
		/// </summary>
		public KeywordCollection(Keyword root, IList<Keyword> list)
			: base(list)
		{
			this.root = root;
		}
		#endregion

		#region Methods
		protected override void ClearItems()
		{
			if (Count > 0)
			{
				base.ClearItems();

				OnChanged(EventArgs.Empty);
			}
		}

		protected override void InsertItem(int index, DaveSexton.DocProject.Keyword item)
		{
			base.InsertItem(index, item);

			OnChanged(EventArgs.Empty);
		}

		protected override void SetItem(int index, Keyword item)
		{
			base.SetItem(index, item);

			OnChanged(EventArgs.Empty);
		}

		protected override void RemoveItem(int index)
		{
			base.RemoveItem(index);

			OnChanged(EventArgs.Empty);
		}
		#endregion

		#region Events
		private readonly object ChangedEventLock = new object();
		private EventHandler ChangedEvent;

		/// <summary>
		/// Event raised when the collection changes.
		/// </summary>
		public event EventHandler Changed
		{
			add
			{
				lock (ChangedEventLock)
				{
					ChangedEvent += value;
				}
			}
			remove
			{
				lock (ChangedEventLock)
				{
					ChangedEvent -= value;
				}
			}
		}

		/// <summary>
		/// Raises the <see cref="Changed" /> event.
		/// </summary>
		/// <param name="e"><see cref="EventArgs" /> object that provides the arguments for the event.</param>
		private void OnChanged(EventArgs e)
		{
			EventHandler handler = null;

			lock (ChangedEventLock)
			{
				handler = ChangedEvent;
			}

			if (handler != null)
				handler(this, e);
		}
		#endregion
	}
}
